package cn.com.xinjinfu.pdoulcProduct.fragment.MyInviest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct.FixedProductInfo;
import cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct.TransferProductInfo;
import cn.com.xinjinfu.pdoulcProduct.adapter.MyInvestUniversalListAdaper;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.MyInvestListBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.fragment.BaseFragment;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView;

/**
 * 已结束列表
 * Created by android-adt on 2015/12/31.
 */
public class FinishListFragment extends BaseFragment implements XListView.IXListViewListener {
    private View viewFragment;
    private Handler mHandler;
    private Activity mActivity;
    private XListView xListView = null;
    private MyInvestUniversalListAdaper investAdapter;
    private MyInvestListBean myInvestListBean;
    private List<MyInvestListBean.TermList> page;
    private RequestQueue requen;
    private int i;
    private int status;
    private LinearLayout no_invest_view;
    private MyInvestListBean.TermList termList;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewFragment = inflater.inflate(R.layout.universal_list, null);
        i = 1;
        no_invest_view = (LinearLayout) viewFragment.findViewById(R.id.no_invest_view);
        return viewFragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
    }

    private void initViews() {
        //ListView
        xListView = (XListView) viewFragment.findViewById(R.id.xListView);
        xListView.setPullLoadEnable(true);// 是否显示下拉刷新和上啦加载
        xListView.setPullRefreshEnable(true);
        investAdapter = new MyInvestUniversalListAdaper(mActivity);
//        investAdapter.setList(page);
//        investAdapter.notifyDataSetChanged();
        xListView.setAdapter(investAdapter);
        xListView.setXListViewListener(this);
        mHandler = new Handler();

        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position>0) {
                    termList = page.get(position - 1);
                    status = termList.getBidStatus();
                    if (status == 1) {             //投标中（定期）
                        startFixedInfoAct();
                    } else if (status == 2) {        //待放款（定期）
                        startFixedInfoAct();
                    } else if (status == 3) {          //转让中（转让）
                        startAssignmentInfoAct();
                    } else if (status == 4) {          //已转出
                        startAssignmentInfoAct();
                    } else if (status == 5) {          //回款中
                        if (termList.getTransferNumber() > 0) {
                            startAssignmentInfoAct();
                        }//（转让）
                        else {
                            startFixedInfoAct();
                        }
                    } else if (status == 6) {          //已结束
                        if (termList.getBidfirstOrreturn() == 1) {
                            startAssignmentInfoAct();
                        } else {
                            startFixedInfoAct();
                        }
                    } else if (status == 7) {
                        startAssignmentInfoAct();
                    }
                }
            }
        });
    }

    /**
     * ***********转到定期标详情*********************
     */
    public void startFixedInfoAct() {
        Intent intent = new Intent();
        intent.putExtra("rettonStyle", "1");
        intent.putExtra("bidId", termList.getBidId() + "");
        intent.putExtra("status", status + "");
        intent.putExtra("investId", termList.getInvestId() + "");
        startActivity(intent.setClass(mActivity, FixedProductInfo.class));
    }

    /**
     * ***********转到转让标详情*********************
     */
    public void startAssignmentInfoAct() {
        Intent intent = new Intent();
        intent.putExtra("rettonStyle", "1");
        intent.putExtra("bidId", termList.getBidId() + "");
        intent.putExtra("bidStatus", status + "");
        intent.putExtra("investId", termList.getInvestId() + "");
        startActivity(intent.setClass(mActivity, TransferProductInfo.class));
    }

    /**
     * 网络请求
     */
    private void loginRequest(String currPage) {
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1213");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("regularType", "3");//投标中时1，汇款中2，已结束3
            parameters.put("currPage", currPage);
            parameters.put("pageSize", "5");
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            DataHandler.errorHandler(mActivity, error);
            onLoad();
            i--;
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            myInvestListBean =JSON.parseObject(jobj.toString(), MyInvestListBean.class);
            if (i == 1){
                page = myInvestListBean.getTermList();
                if (!page.isEmpty()) {
                    no_invest_view.setVisibility(View.GONE);
                } else {
                    no_invest_view.setVisibility(View.VISIBLE);
                }
                investAdapter.setList(page);
                investAdapter.notifyDataSetChanged();
            }else {
                upMoreData();
            }
            onLoad();

        }
    };
    public void upMoreData(){
        List<MyInvestListBean.TermList> newpage = myInvestListBean.getTermList();
        if (newpage.isEmpty()){
            ToastManager.showShort(mActivity, "没有更多数据");}
        else {page.addAll(newpage);}
        investAdapter.setList(page);
        investAdapter.notifyDataSetChanged();
    }

    private void onLoad() {
        xListView.stopRefresh();
        xListView.stopLoadMore();
        xListView.setRefreshTime("刚刚");
    }

    @Override
    public void onRefresh() {
        i = 1;
        loginRequest(i+"");
    }

    @Override
    public void onLoadMore() {
        loginRequest("" + (++i));
    }

    @Override
    protected void lazyLoad() {
        i = 1;
        requen = Volley.newRequestQueue(mActivity);
        loginRequest(i+"");
    }

    @Override
    public String getFragmentName() {
        return null;
    }

}
